package com.example.demo2.demo02;

import com.example.demo2.rabbitmq.RabbitMQConnection;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 消费者 - 非公平队列 - 手动应答(autoAck= false)
 * @Author: mingtian
 * @CreateDate: 2021/1/16 09:34
 * @Version: 1.0
 */
public class Consumer2 {
    /**
     * 队列名称
     */
    private static final String QUEUE_NAME = "test_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.创建连接
        Connection connection = RabbitMQConnection.getConnection();
        // 2.设置通道
        Channel channel = connection.createChannel();
        // 指定我们消费者每次批量获取消息的数量
        channel.basicQos(1);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    // 模拟耗时
                    Thread.sleep(100);
                } catch (Exception e) {
                }
                String msg = new String(body, "UTF-8");
                System.out.println("消费者获取消息:" + msg);
                // 消费者完成之后，通知 MQ 服务器端 删除该消息 手动应答模式
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        // 3.监听队列  autoAck true:自动应答  false:手动应答
        channel.basicConsume(QUEUE_NAME, false, defaultConsumer);

    }
}